package com.chaos.framework.app.helper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chaos.framework.model.dto.DTO;
import com.chaos.framework.model.dto.page.PageList;
import com.chaos.framework.model.dto.page.PageQueryDto;
import com.chaos.framework.model.dto.page.RainBowPageList;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jacky
 * @date 2020/7/2 21:28
 */
public class PageHelper {
    public static Page page(PageQueryDto query) {
        return new Page(query.getPageNum(), query.getPageSize());
    }

    public static <T> PageList pageList(IPage<T> page, Class c) {
        return PageList.builder().current(page.getCurrent()).total(page.getTotal()).list(toList(page.getRecords(), c)).build();
    }

    public static <T> PageList pageList(IPage<T> page) {
        return PageList.builder().current(page.getCurrent()).total(page.getTotal()).list((List<Object>) page.getRecords()).build();
    }

    public static <T> RainBowPageList rainBowPageList(IPage<T> page, Class c, T top, T down) {
        RainBowPageList rainBowPageList = new RainBowPageList();
        rainBowPageList.setList(toList(page.getRecords(), c));
        rainBowPageList.setTotal(page.getTotal());
        rainBowPageList.setCurrent(page.getCurrent());
        rainBowPageList.setDown(down);
        rainBowPageList.setTop(top);
        return rainBowPageList;

    }

    public static <T> RainBowPageList rainBowPageList(IPage<T> page, T top, T down) {
        RainBowPageList rainBowPageList = new RainBowPageList();
        rainBowPageList.setList(page.getRecords());
        rainBowPageList.setTotal(page.getTotal());
        rainBowPageList.setCurrent(page.getCurrent());
        rainBowPageList.setDown(down);
        rainBowPageList.setTop(top);
        return rainBowPageList;
    }

    private static <T> List toList(List<T> list, Class c) {
        return list.stream().map(entity -> {
            DTO t = null;
            try {
                t = (DTO) c.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            BeanUtils.copyProperties(entity, t);
            return t;
        }).collect(Collectors.toList());
    }

}
